package com.wcs.exam.controller.admin.biz;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.wcs.exam.common.base.BaseBiz;
import com.wcs.exam.common.base.Result;
import com.wcs.exam.common.base.page.Page;
import com.wcs.exam.common.base.page.PageUtil;
import com.wcs.exam.common.cache.CacheRedis;
import com.wcs.exam.common.constant.RedisConstant;
import com.wcs.exam.common.util.BeanUtil;
import com.wcs.exam.common.util.Sha1Util;
import com.wcs.exam.controller.admin.req.*;
import com.wcs.exam.controller.admin.resp.AdminSysUserPageResp;
import com.wcs.exam.controller.admin.resp.AdminSysUserViewResp;
import com.wcs.exam.controller.biz.SysConfigCommonBiz;
import com.wcs.exam.controller.biz.SysUserCommonBiz;
import com.wcs.exam.dao.SysRoleDao;
import com.wcs.exam.dao.SysRoleUserDao;
import com.wcs.exam.dao.SysUserDao;
import com.wcs.exam.dao.impl.mapper.entity.SysMenu;
import com.wcs.exam.dao.impl.mapper.entity.SysRole;
import com.wcs.exam.dao.impl.mapper.entity.SysRoleUser;
import com.wcs.exam.dao.impl.mapper.entity.SysUser;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Admin-后台用户信息
 *
 * @author wcs
 * @since 2024-07-06
 */
@Component
@RequiredArgsConstructor
public class AdminSysUserBiz extends BaseBiz {

    @NotNull
    private final SysUserDao dao;
    @NotNull
    private final SysRoleUserDao sysRoleUserDao;
    @NotNull
    private final SysRoleDao sysRoleDao;

    @NotNull
    private final SysUserCommonBiz sysUserCommonBiz;
    @NotNull
    private final SysConfigCommonBiz sysConfigCommonBiz;
    @NotNull
    private final CacheRedis cacheRedis;

    /**
     * 后台用户信息-分页
     *
     * @param req 后台用户信息-分页查询参数
     * @return 后台用户信息
     */
    public Result<Page<AdminSysUserPageResp>> page(AdminSysUserPageReq req) {
        // 处理查询条件
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(req.getMobile()), SysUser::getMobile, req.getMobile());

        // 排序
        wrapper.orderByDesc(SysUser::getSort).orderByDesc(SysUser::getId);

        // 分页查询
        IPage<SysUser> page = dao.page(PageDTO.of(req.getPageCurrent(), req.getPageSize()), wrapper);
        Page<AdminSysUserPageResp> resp = PageUtil.transform(page, AdminSysUserPageResp.class);
        if (CollectionUtil.isNotEmpty(resp.getList())) {
            List<Long> userIdList = resp.getList().stream().map(AdminSysUserPageResp::getId).collect(Collectors.toList());
            List<SysRoleUser> roleUserList = sysRoleUserDao.listByUserIds(userIdList);
            if (CollUtil.isNotEmpty(roleUserList)) {
                List<Long> roles = roleUserList.stream().map(SysRoleUser::getRoleId).collect(Collectors.toList());
                List<SysRole> roleList = sysRoleDao.listByIds(roles);
                extracted(resp, roleUserList, roleList);
            }
        }

        // 处理分页响应信息
        return Result.success(resp);
    }

    private void extracted(Page<AdminSysUserPageResp> respPage, List<SysRoleUser> roleUserList, List<SysRole> roleList) {
        if (CollUtil.isNotEmpty(roleList)) {
            Map<Long, String> roleNameMap = roleList.stream().collect(Collectors.toMap(SysRole::getId, SysRole::getRoleName));
            Map<Long, List<Long>> map = roleUserList.stream().collect(Collectors.groupingBy(SysRoleUser::getUserId, Collectors.mapping(SysRoleUser::getRoleId, Collectors.toList())));
            for (AdminSysUserPageResp resp : respPage.getList()) {
                List<Long> roleIdList = map.get(resp.getId());
                if (CollUtil.isNotEmpty(roleIdList)) {
                    List<String> roleNameList = new ArrayList<>();
                    for (Long roleId : roleIdList) {
                        roleNameList.add(roleNameMap.get(roleId));
                    }
                    resp.setRoleNameList(roleNameList);
                }
            }
        }
    }

    /**
     * 后台用户信息-添加
     *
     * @param req 后台用户信息-添加对象
     * @return 添加结果
     */
    public Result<String> save(AdminSysUserSaveReq req) {
        SysUser record = dao.getByMobile(req.getMobile());
        if (ObjectUtil.isNotNull(record)) {
            return Result.error("用户已添加成管理员");
        }

        // 解密
        String mobilePsw = sysConfigCommonBiz.decrypt(req.getMobilePwdEncrypt());
        if (!StringUtils.hasText(mobilePsw)) {
            return Result.error("密码不能为空");
        }
        SysUser sysUser = BeanUtil.copyProperties(req, SysUser.class);
        sysUser.setMobileSalt(IdUtil.simpleUUID());
        sysUser.setMobilePsw(Sha1Util.getSign(sysUser.getMobileSalt() + mobilePsw));
        sysUser.setSort(dao.getMaxSort() + 1);
        boolean saveRes = dao.save(sysUser);
        return saveRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 后台用户信息-查看
     *
     * @param id 主键ID
     * @return 后台用户信息
     */
    public Result<AdminSysUserViewResp> view(Long id) {
        SysUser sysUser = dao.getById(id);
        if (ObjectUtil.isNull(sysUser)) {
            return Result.error(toI18n("system.sys.user.not.exist"));
        }
        AdminSysUserViewResp resp = BeanUtil.copyProperties(sysUser, AdminSysUserViewResp.class);
        // 列出菜单
        List<SysMenu> sysMenus = sysUserCommonBiz.listMenu(sysUser.getId());
        // 路由
        resp.setRouterList(sysUserCommonBiz.routerList(sysMenus));
        // 菜单
        resp.setMenuList(sysUserCommonBiz.menuList(sysMenus));
        // 权限
        resp.setPermissionList(sysMenus.stream().map(SysMenu::getPermission).filter(StringUtils::hasText).collect(Collectors.toList()));
        // 获取接口权限，放入缓存
        List<String> apis = sysMenus.stream().map(SysMenu::getApis).filter(StringUtils::hasText).collect(Collectors.toList());
        cacheRedis.set(RedisConstant.System.ADMIN_APIS.concat(sysUser.getId().toString()), apis, 1, TimeUnit.DAYS);
        return Result.success(resp);
    }

    /**
     * 后台用户信息-编辑
     *
     * @param req 后台用户信息-编辑对象
     * @return 编辑结果
     */
    public Result<String> edit(AdminSysUserEditReq req) {
        // 获取校验后台用户信息
        SysUser sysUser = dao.getById(req.getId());
        if (ObjectUtil.isNull(sysUser)) {
            return Result.error(toI18n("system.sys.user.not.exist"));
        }

        // 更新后台用户信息
        SysUser updateSysUser = BeanUtil.copyProperties(req, SysUser.class);
        updateSysUser.setGmtCreate(null);
        updateSysUser.setGmtModified(null);
        boolean updateRes = dao.updateById(updateSysUser);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 后台用户信息-编辑更新状态
     *
     * @param req 后台用户信息-编辑更新状态
     * @return 编辑结果
     */
    public Result<String> updateStatus(AdminSysUserUpdateStatusReq req) {
        // 获取校验后台用户信息
        SysUser sysUser = dao.getById(req.getId());
        if (ObjectUtil.isNull(sysUser)) {
            return Result.error(toI18n("system.sys.user.not.exist"));
        }

        // 更新后台用户信息
        SysUser updateSysUser = BeanUtil.copyProperties(req, SysUser.class);
        updateSysUser.setGmtCreate(null);
        updateSysUser.setGmtModified(null);
        boolean updateRes = dao.updateById(updateSysUser);
        return updateRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    /**
     * 后台用户信息-排序
     *
     * @param reqs 后台用户信息-排序对象
     * @return 排序结果
     */
    public Result<String> sort(List<AdminSysUserSortReq> reqs) {
        // 查询获取后台用户信息
        List<SysUser> sysUserList = dao
                .lambdaQuery()
                .in(SysUser::getId, reqs.stream().map(AdminSysUserSortReq::getId).collect(Collectors.toSet()))
                .list();
        if (CollectionUtil.isEmpty(sysUserList)) {
            return Result.success(toI18nSuccess());
        }

        // 处理待更新排序的后台用户信息
        Map<Long, Integer> sortMap = new HashMap<>();
        reqs.forEach(item -> sortMap.put(item.getId(), item.getSort()));
        List<SysUser> updateList = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            Integer sort = sortMap.get(sysUser.getId());
            if (ObjectUtil.isNull(sort)) {
                continue;
            }

            SysUser updateSysUser = new SysUser();
            updateSysUser.setId(sysUser.getId());
            updateSysUser.setSort(sort);
            updateList.add(updateSysUser);
        }

        // 批量更新后台用户信息排序
        if (CollectionUtil.isNotEmpty(updateList)) {
            dao.updateBatchById(updateList);
        }
        return Result.success(toI18nSuccess());
    }


    /**
     * 用户信息-删除
     *
     * @param id 主键ID
     * @return 删除结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<String> delete(Long id) {
        // 获取校验用户信息
        SysUser sysUser = dao.getById(id);
        if (ObjectUtil.isNull(sysUser)) {
            return Result.error(toI18n("system.sys.role.not.exist"));
        }
        // 删除用户信息
        boolean deleteRes = dao.removeById(id);
        return deleteRes ? Result.success(toI18nSuccess()) : Result.error(toI18nFail());
    }

    public Result<String> password(AdminSysUserPasswordReq req) {
        SysUser record = dao.getById(req.getUserId());
        if (ObjectUtil.isNull(record)) {
            return Result.error(toI18n("system.sys.user.not.exist"));
        }

        // 解密
        String mobilePsw = sysConfigCommonBiz.decrypt(req.getMobilePwdEncrypt());
        if (!StringUtils.hasText(mobilePsw)) {
            return Result.error("密码不能为空");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(req.getUserId());
        sysUser.setMobileSalt(IdUtil.simpleUUID());
        sysUser.setMobilePsw(Sha1Util.getSign(sysUser.getMobileSalt() + mobilePsw));
        dao.updateById(sysUser);
        return Result.success("操作成功");
    }
}
